package com.yYclass.controller;


import com.google.code.kaptcha.Producer;
import com.yYclass.component.SmsComponent;
import com.yYclass.controller.request.AccountLoginRequest;
import com.yYclass.controller.request.AccountRegisterRequest;
import com.yYclass.enums.BizCodeEnum;
import com.yYclass.enums.SendCodeEnum;
import com.yYclass.service.AccountService;
import com.yYclass.service.FileService;
import com.yYclass.util.CommonUtil;
import com.yYclass.util.JsonData;
import com.yYclass.vo.SendCodeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 栗永松
 * @since 2024-04-09
 */
@Slf4j
@RestController
@RequestMapping("/accountDO")
public class AccountController {

    @Autowired
    private SmsComponent component;

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private AccountService accountService;
    /**
     * 验证码过期时间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 1000 * 10 *  60;

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public JsonData uploadImage(@RequestPart("file")MultipartFile file){
       String result = fileService.uploadImage(file);
        JsonData jsonData = result != null ? JsonData.buildSuccess(result) : JsonData.buildResult(BizCodeEnum.FILE_UPLOAD_USER_IMG_FAIL);
        return jsonData;
    }

    @RequestMapping("/testM")
    public String testM(){
        component.test();
        return "ok";
    }

    @RequestMapping("/demo")
    public String test(){
        component.send("17600365830","测试一下怎么样了");
        return "ok";
    }

    /**
     * 生成验证码
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request,HttpServletResponse response){
        String text = captchaProducer.createText();
        log.info("验证码内容:{}",text);
        //存储redis,配置过期时间 ， jedis/lettuce
        redisTemplate.opsForValue().set(getCaptchaKey(request),text,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        BufferedImage image = captchaProducer.createImage(text);
        try(ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取流出错:{}",e.getMessage());
        }
    }
    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "account-service:captcha:"+CommonUtil.MD5(ip+userAgent);
        log.info("验证码key:{}",key);
        return key;
    }

    /**
     * 发送短信功能
     * @param sendCodeRequest
     * @param request
     * @return
     */
    @RequestMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest,HttpServletRequest request) {
        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        String captcha = sendCodeRequest.getCaptcha();
        if (captcha != null && cacheCaptcha != null && cacheCaptcha.equals(captcha)){
            redisTemplate.delete(key);
            JsonData jsonData = accountService.sendCode(SendCodeEnum.USER_REGISTER,sendCodeRequest.getTo());
            return jsonData;
        }else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }

    /**
     * 用户注册
     * @param registerRequest
     * @return
     */
    @PostMapping("register")
    public JsonData register(@RequestBody AccountRegisterRequest registerRequest){

        JsonData jsonData = accountService.register(registerRequest);
        return jsonData;
    }
    /**
     * 用户登录
     * @param request
     * @return
     */
    @PostMapping("login")
    public JsonData login(@RequestBody AccountLoginRequest request){

        JsonData jsonData = accountService.login(request);
        return jsonData;
    }
}

